<template>
  <div>
    <el-dialog
      v-model="canUseAddInfo.openObj.visible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <template #header>
        <div class="dialog_title">
          <div class="blueLine"></div>
          <div class="title">{{ canUseAddInfo.openObj.openTitle }}</div>
        </div>
      </template>
      <div class="table_container">
        <div class="table_top_btn">
          <div>
            {{ t("common.currentSelected") }}: {{ toBeSendList.length }}
            {{ t("common.itemsSuffix") }}
          </div>
          <right-toolbar
            @queryTable="queryList"
            :searchConfig="canUseAssetsInfo.searchInfo"
            :columns.sync="canUseAddInfo.columns"
            @search="handleSearch"
            drawerWidth="45%"
            class="dialog_toolbar"
          >
          </right-toolbar>
        </div>

        <div class="table_area">
          <el-table
            ref="assetsTableRef"
            style="width: 100%"
            height="400"
            v-loading="canUseAssetsInfo.loading"
            :data="canUseAssetsInfo.data"
            @selection-change="handleSelectionChange"
            :row-class-name="getRowClass"
            @row-click="handleRowChick"
            :row-key="rowKey"
            :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
              fixed
              :reserve-selection="true"
            />
            <template v-for="(item, index) in canUseAddInfo.columns" :key="item.key">
              <el-table-column
                v-if="item.visible"
                :prop="item.prop"
                 :label="t(`tableColumns.${item.langKey}`)"
                :width="item.width"
                :show-overflow-tooltip="true"
              >
                <template #default="{ row }">
                  <el-tag
                    v-if="item.prop == 'enableFlag'"
                    :type="
                      row.enableFlag == 0
                        ? 'success'
                        : row.enableFlag == 1 ||
                          row.enableFlag == 3 ||
                          row.enableFlag == 4
                        ? 'warning'
                        : 'danger'
                    "
                  >
                    {{ row.enableFlagName }}
                  </el-tag>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="pagination-area">
          <pagination
            :total="canUseAssetsInfo.page.total"
            v-model:page="canUseAssetsInfo.page.pageNum"
            v-model:limit="canUseAssetsInfo.page.pageSize"
            @pagination="queryList"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSend">{{
            t("common.confirm")
          }}</el-button>
          <el-button @click="cancelSend">{{ t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ashAssetsDialog">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { ArrowLeft, Delete } from "@element-plus/icons-vue";
import RightToolbar from "@/components/RightToolbar";
import { GetAssetsList } from "@/api/assetsManage/assetsList";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import { GetUserInfoAll } from "@/api/sys/user";
import { getUserInfo } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { inject, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["submitSend", "queryCanUseAssetsData"]);
const canUseAssetsInfo = inject("canUseAssetsInfo");
const props = defineProps({
  canUseAddInfo: {
    type: Object,
  },
  selectedAssets: {
    //默认来自父组件的,所选assetsId数组
    type: Array,
    default: () => [],
  },
});
const assetsTableRef = ref(null); //表格dom
const toBeSendList = ref([]); //待发送的数据给addOrEdit

// 设置默认勾选
const setDefaultSelections = () => {
  toBeSendList.value = canUseAssetsInfo.data.filter((item) =>
    props.selectedAssets.includes(item.assetsId)
  );
  toBeSendList.value.forEach((item) => {
    if (assetsTableRef.value) {
      assetsTableRef.value.toggleRowSelection(item, true);
    }
  });
};

watch(
  () => canUseAssetsInfo.data,
  (newData, oldData) => {
    if (newData !== oldData) {
      setDefaultSelections();
    }
  }
);

// 在mounted执行更新
onMounted(() => {
  setDefaultSelections();
});
const rowKey = (row) => {
  //根据rowKey高亮
  return row.assetsId;
};
// 1111获取的可领用列表
const queryList = async () => {
  emit("queryCanUseAssetsData");
};

const handleSearch = () => {
  queryList();
};
//发送数据
const submitSend = async () => {
  // 将状态信息传递给父组件
  const result = toBeSendList.value.map((item) => {
    const existingItem = props.selectedAssets.find((e) => e.assetsId === item.assetsId);
    if (existingItem) {
      return { ...item, state: existingItem.state === 1 ? 1 : 0 };
    } else {
      return { ...item, state: 0 };
    }
  });
  emit("submitSend", result);
  console.log("结果", result);
  proxy.canUseAddInfo.openObj.visible = false;
  toBeSendList.value = [];
};
//取消发送
const cancelSend = () => {
  proxy.canUseAddInfo.openObj.visible = false;
};

const handleSelectionChange = (e) => {
  // console.log('选择', e)
  toBeSendList.value = e;
};
const getRowClass = ({ row }) => {
  return proxy.rowClass(row, toBeSendList.value, "assetsId");
};

const handleRowChick = (row) => {
  const selected = toBeSendList.value.some((item) => item.assetsId === row.assetsId);
  if (!selected) {
    toBeSendList.value.push(row);
    assetsTableRef.value.toggleRowSelection(row);
  } else {
    const finArr = toBeSendList.value.filter((item) => {
      return item.assetsId !== row.assetsId;
    });
    toBeSendList.value = finArr;
    assetsTableRef.value.toggleRowSelection(row, false);
  }
};

defineExpose({
  toBeSendList,
  assetsTableRef,
});
</script>
<style lang="scss" scoped>
.dialog_title {
  display: flex;
  font-weight: 700;

  .blueLine {
    color: #1065ff;
    background: #1065ff;
    width: 5px;
    height: auto;
    border-radius: 3px;
    margin-right: 10px;
  }
  .title {
    color: #000;
  }
}

:deep(.el-dialog__body) {
  padding: 0 20px;
}
:deep(.dialog-footer) {
  padding-top: 70px !important;
}

.table_container {
  padding: 0;
  .pagination-area {
    display: flex;
    width: 100%;
    position: relative;
  }
}
.dialog_toolbar {
  > :deep(div:first-child) {
    > div {
      position: absolute;
    }
  }
}
</style>
